package org.sample.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.sample.commons.ResultCodes;
import org.sample.commons.bean.BeanUtils;
import org.sample.commons.lang.HashUtils;
import org.sample.dao.UserDao;
import org.sample.entity.User;
import org.sample.model.exception.APIException;
import org.sample.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao dao;

    @Override
    public User login(String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password))
            throw new APIException(ResultCodes.UnameOrPwdError);
        User entity = new User(username);
        entity = dao.findOne(Example.of(entity)).get();
        if (entity == null)
            throw new APIException(ResultCodes.UnameOrPwdError);
        password = HashUtils.md5(password);
        if (!password.equalsIgnoreCase(entity.getPassword()))
            throw new APIException(ResultCodes.UnameOrPwdError);
        return entity;
    }

    @Override
    public List<User> getIdNameList() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void logicalDelete(Integer id) {
        User entity = dao.getOne(id);
        entity.setDeleted(true);
        dao.save(entity);
    }

    @Override
    public User saveNotNull(User entity) {
        if (entity.getId() == null) {
            return dao.save(entity);
        }
        User oldEntity = dao.getOne(entity.getId());
        BeanUtils.copyBeanNotNull(entity, oldEntity);
        return dao.save(oldEntity);
    }

}